package agent

import (
	"mime/multipart"
	"strconv"

	"github.com/gofiber/fiber/v2"
	logger "github.com/sirupsen/logrus"

	"publish-manage/internal/service"
	"publish-manage/pkg/domain"
)

var PublishController = new(publishController)

type publishController struct{}

func (*publishController) Publish(ctx *fiber.Ctx) error {
	form, err := ctx.MultipartForm()
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "解析参数失败",
		})
	}
	pps := form.Value["path"]
	if len(pps) == 0 {
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "path部署路径必须提供",
		})
	}
	pp := pps[0]
	ts := form.Value["type"]
	t := 1
	if len(ts) > 0 {
		t, _ = strconv.Atoi(ts[0])
	}
	cmds := form.Value["cmd"]
	cmd := ""
	if len(cmds) > 0 {
		cmd = cmds[0]
	}

	zipDirs := form.Value["zipDir"]
	zipDir := ""
	if len(zipDirs) > 0 {
		zipDir = zipDirs[0]
	}

	var fh *multipart.FileHeader

OUT:
	for _, fd := range form.File {
		for i := 0; i < len(fd); i++ {
			fh = fd[i]
			break OUT
		}
	}

	if fh == nil {
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "请提供上传文件",
		})
	}

	var file multipart.File
	file, err = fh.Open()
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "读取文件发生错误",
		})
	}
	defer file.Close()

	if err = service.AgentPublishService.Publish(t, file, fh.Size, pp, zipDir, cmd); err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "部署文件发生错误",
		})
	}
	return ctx.JSON(&domain.CommonResponse{})
}
